﻿using System.Web.Mvc;
using MVCCricketWorldCupTrivia.Models;
using System.Configuration;

namespace MVCCricketWorldCupTrivia.Controllers
{
    public class QuestionController : Controller
    {
        public ActionResult Play(int? attackLevel)
        {
            //If there is no attack level for this game lets set it to the 
            //start attack level
            if (!attackLevel.HasValue || attackLevel ==0)
            {
                attackLevel = GameSettings.StartAttackLevel;
            }
        
            //Get the next question 
            Question question = Question.GetNextQuestion(attackLevel.Value);
            if (HttpContext.Session["Game"] == null)
            {
                //No game in the session so lets create it 
                Game game = new Game();
                game.CreateGame();
                question.CurrentGame = game;
                question.AttackLevel = attackLevel.Value;
            }
         
            return View(question);
        }

        [HttpPost]
        public ActionResult Play(Question question)
        {
            if (question.CurrentGame == null)
            {
                return RedirectToAction("Index", "Home");
            }
        
            //get the shot result for by calling the getresult method
            ShotResult result = question.CurrentGame.GetResult(question);
            if (result.Out)
            {            
                question.CurrentGame.Wickets++;
            }
            else
            {
                question.CurrentGame.Runs += result.Runs;
            }

            //Increment the Overs then check if the game is over
            question.CurrentGame.Overs++;
            if (question.CurrentGame.Overs >= GameSettings.MaxOvers||
                question.CurrentGame.Wickets >= GameSettings.MaxWickets||
                question.CurrentGame.Runs > question.CurrentGame.SriLankaScore)
            {
                return View("Complete",question.CurrentGame);
            }
            
            //Next over will begin
            return RedirectToAction("Play",
                    new {AttackLevel = question.AttackLevel});
        }
    }
}
